package com.xieyong.leetcode;

public class Leetcode3439 {
    public static void main(String[] args) {
        Leetcode3439 leetcode3439 = new Leetcode3439();
//        int eventTime = 10;
//        int k = 1;
//        int[] startTime = {0,2,9};
//        int[] endTime = {1,4,10};
        int eventTime = 21;
        int k = 1;
        int[] startTime = {7,10,16};
        int[] endTime = {10,14,18};
        int i = leetcode3439.maxFreeTime(eventTime, k, startTime, endTime);
        System.out.println(i);
    }


    public int maxFreeTime(int eventTime, int k, int[] startTime, int[] endTime) {
        int res = 0;
        int n = startTime.length;
        int[] timelist = new int[n + 1];
        timelist[0] = startTime[0];
        int index = 1;
        for (int i = 0,j = 0; i < n - 1 && j < n;) {
            i++;
            timelist[index] = startTime[i] - endTime[j];
            j++;
            index++;
        }
        timelist[index] = eventTime - endTime[n - 1];
        int left = 0, right = k;
        int firsttime = 0;
        for (int i = 0; i <= k; i++) {
            firsttime += timelist[i];
        }
        res = Math.max(res, firsttime);
        while (right < n) {
            int del = timelist[left];
            int add = timelist[right + 1];
            int newtime = firsttime - del + add;
            res = Math.max(res, newtime);
            left++;
            right++;
            firsttime = newtime;
        }
        for (int i : timelist) {
            System.out.print(i + "  ");
        }
        System.out.println();
        return res;
    }
}
